//
//  HomeViewController.m
//  SDSY
//
//  Created by 蓝布鲁 on 2017/3/17.
//  Copyright © 2017年 蓝布鲁. All rights reserved.
//

#import "HomeViewController.h"
#import "SDCycleScrollView.h"
#import "FunctionButton.h"
#import "ClassifyButton.h"
#import "ActivityCell.h"
#import "NoticeTableViewController.h"
#import "OrderActivityController.h"
#import "PastActivityViewController.h"
#import "OrderTeacherController.h"
#import "BannerModel.h"
#import "SigninViewController.h"
#import "ActivityInfoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UserInfoModel.h"


@interface HomeViewController () <SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
// 数据相关
@property (nonatomic,assign) BOOL isHasNewMessage;                  // 是否有新消息(新消息+未读消息)
@property (nonatomic,retain) NSMutableArray *bannerArray;           // banner模型数组
@property (nonatomic, retain) NSMutableArray *recommandArray;       // 推荐活动模型数组
@property (nonatomic, retain) NSMutableArray *recentArray;          // 近期活动模型数组
@property (nonatomic,assign) NSInteger page;

// 视图相关
@property (nonatomic,retain) UIView *headerView;                    // tableView的headerView
@property (nonatomic,retain) SDCycleScrollView *bannerView;         // 顶部轮播图
@property (nonatomic,retain) UITableView *tableView;                // 近期&推荐tableView

@end

@implementation HomeViewController

#pragma mark - 初始化方法
-(instancetype)init{
    if (self==[super init]) {
        // 1.设置标题&TabBar图标
        self.title = @"首页";
        self.tabBarItem.image = [UIImage imageNamed:@"home_tabBar"];
        self.hidesBottomBarWhenPushed = false;
    }
    return self;
}

#pragma mark - 系统回调方法
- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.设置导航栏消息按钮
    [self setupMessageBtn];

    // 2.设置签到按钮
    [self setupSigninBtn];
    
    // 3.设置View布局
    [self setupView];
    
    // 4.网络请求
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 4.1获取banner数据
        [self updateBanner];
        
        // 4.2获取推荐活动属性
        [self updateRecommandActivity];
        
        // 4.3获取近期活动属性
        self.page = 0;
        [self updateRecentActivityPage:self.page getCount:6];
        
        [self.tableView.mj_header performSelector:@selector(endRefreshing) withObject:nil afterDelay:0.8];
    }];
    [self.tableView.mj_header beginRefreshing];

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 上拉加载近期活动
        self.page++;
        [self updateRecentActivityPage:self.page getCount:6];
    }];
}

#pragma mark - 自定义方法

/**
 * @brief 设置导航栏消息按钮
 */
- (void)setupMessageBtn {
#pragma mark 待改进!!!!
    // 1.获取是否有最新消息尚未拉取
    
    // 2.判断是否已存在未读消息
    self.isHasNewMessage = false;
    
    // 3.初始化消息按钮
    if (self.isHasNewMessage) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"message_new"] style:UIBarButtonItemStylePlain target:self action:@selector(messageBtnTapped)];
    }else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"message_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(messageBtnTapped)];
    }
}
/**
 * @brief 设置签到按钮
 */

-(void)setupSigninBtn {
    UIBarButtonItem *messageItem = self.navigationItem.rightBarButtonItem;
    UIBarButtonItem *signinItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"scan_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(signinBtnTapped)];
    self.navigationItem.rightBarButtonItems = @[messageItem,signinItem];
}

/**
 * @brief 设置View布局
 */
- (void)setupView {
    // 1.设置headerView
    self.headerView = [[UIView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    
    // 2.设置顶部轮播图
    self.bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) delegate:self placeholderImage:[UIImage imageNamed:@"Error"]];
    self.bannerView.infiniteLoop = true;
    self.bannerView.autoScrollTimeInterval = 5.0;
    self.bannerView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    [self.headerView addSubview:self.bannerView];
    
    // 3.设置功能Btn组(活动预约\导师预约\往期活动)
    UIView *funcationBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bannerView.bottomY, SCREEN_WIDTH, 150)];
    // 3.1.活动预约Btn
    FunctionButton *orderActivityBtn = [[FunctionButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 150)
                                                                 title:@"活动预约"
                                                       backgroundImage:[UIImage imageNamed:@"orderActivityBtn_background"]
                                                            buttonType:FunctionButtonHalfVerticalType];
    [orderActivityBtn addTarget:self action:@selector(orderActivityBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    [funcationBtnView addSubview:orderActivityBtn];
    
    // 3.2.导师预约Btn
    FunctionButton *orderTeacherBtn = [[FunctionButton alloc] initWithFrame:CGRectMake(orderActivityBtn.rightX, 0, SCREEN_WIDTH / 2, 150)
                                                                 title:@"导师预约"
                                                       backgroundImage:[UIImage imageNamed:@"orderTeacherBtn_background"]
                                                            buttonType:FunctionButtonHalfVerticalType];
    [orderTeacherBtn addTarget:self action:@selector(orderTeacherBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    [funcationBtnView addSubview:orderTeacherBtn];
    
    // 3.3.往期活动Btn
//    FunctionButton *pastActivityBtn = [[FunctionButton alloc] initWithFrame:CGRectMake(orderActivityBtn.rightX, orderTeacherBtn.bottomY, SCREEN_WIDTH-orderActivityBtn.width, 150 * 0.5)
//                                                                title:@"往期活动"
//                                                      backgroundImage:[UIImage imageNamed:@"pastActivityBtn_background"]
//                                                           buttonType:FunctionButtonBigHorizontalType];
//    [pastActivityBtn addTarget:self action:@selector(pastActivityBtnTapped) forControlEvents:UIControlEventTouchUpInside];
//    [funcationBtnView addSubview:pastActivityBtn];
    [self.headerView addSubview:funcationBtnView];
    
    // 4.设置分类Btn组(博雅读书\心情\实践......)
    // 4.1view相关属性计算
    CGFloat width = 70;
    CGFloat height = 60;
    CGFloat xInterval = (SCREEN_WIDTH - width * 3) / 6.0;
    CGFloat yInterval = 5;
    NSInteger btnCount = 6;
    
    // 4.2初始化数据
    NSArray *buttonNameArray = [CLASSIFY_NAME subarrayWithRange:NSMakeRange(1, CLASSIFY_NAME.count-1)];
    NSArray *imageNameArray = CLASSIFY_ICON;
    
    NSInteger allRowCount = (btnCount-1)/3+1;                                   // 所有行数
    CGFloat viewHeight = (yInterval + height) * allRowCount + yInterval;        // (行间隔 + button高度) * 行数 + 行间隔
    UIView *classifyBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, funcationBtnView.bottomY, SCREEN_WIDTH, viewHeight)];
    

    
    
    //4.2设置视图
    for (int i = 0; i < btnCount; i++) {
        // 1.获取行号
        NSInteger row = (i / 3);
        
        // 2.获取列号
        NSInteger column = i % 3;
        
        // 3.计算x坐标: 水平间隔 + (button宽度 + 水平间隔 * 2) * 列号
        CGFloat x = xInterval + (width + xInterval * 2) * column;
        
        // 4.计算y坐标: 竖直间隔 + (button高度 + 竖直间隔) * 行号
        CGFloat y = yInterval + (height + yInterval) * row;
        
        // 5.创建button
        ClassifyButton *btn = [[ClassifyButton alloc] initWithFrame:CGRectMake(x, y, width, height)
                                                              title:buttonNameArray[i]
                                                              image:[UIImage imageNamed:imageNameArray[i]]];
        [btn addTarget:self action:@selector(classifyBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
        // 6.添加button到view
        [classifyBtnView addSubview:btn];
    }

    
    [self.headerView addSubview:classifyBtnView];
    
    // 5.设置推荐&近期活动tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    
    self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, classifyBtnView.bottomY);
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
}

// 如果请求失败,HUD显示错误,tableVIew刷新空数据,foot提示没有数据
- (void)updateFailed {
    [SVProgressHUD showfailed];
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - 网络回调调用方法
-(void)updateBanner {
    self.bannerArray = [[NSMutableArray alloc] init];
    [[NetworkTool shareInstance] requireMethodType:POSTType
                                         URLString:@"SDSY/getBanner"
                                        parameters:@{@"id":@"123",@"code":@1234, @"s_id": [UserInfoModel shareInstance].stu_id}
                                           success:^(NSDictionary *respondDictionary) {
        
        NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
        NSMutableArray *titleArray = [[NSMutableArray alloc] init];
        
        // 1.获得JSON转换为模型
        for (NSDictionary *dic in respondDictionary[@"banners"]) {
            BannerModel *model = [[BannerModel alloc] initWithDictionary:dic];
            // 2.存放URL
            [imageURLArray addObject:model.img_url];
            [titleArray addObject:model.title];
            
            [self.bannerArray addObject:model];
        }
        // 2.刷新banner
        self.bannerView.imageURLStringsGroup = imageURLArray;
        self.bannerView.titlesGroup = titleArray;
        
    } failure:^(NSError *error) {
        
        [SVProgressHUD showfailed];
    }];
}

// 获取推荐活动属性
-(void)updateRecommandActivity {
    self.recommandArray = [[NSMutableArray alloc] init];

    [[NetworkTool shareInstance] requireMethodType:POSTType
                                         URLString:@"SDSY/getRecActivity"
                                        parameters:@{@"s_id": [UserInfoModel shareInstance].stu_id}
                                           success:^(NSDictionary *respondDictionary) {
                                               // 储存数据模型
                                               for (NSDictionary *dictionary in respondDictionary[@"recommandActivity"]) {
                                                   ActivityModel *model = [[ActivityModel alloc] initWithDictionary:dictionary];
                                                   [self.recommandArray addObject:model];
                                               }
                                               [self.tableView reloadData];
                                           } failure:^(NSError *error) {
                
            }];
}

// 获取近期活动属性
-(void)updateRecentActivityPage:(NSInteger)page getCount:(NSInteger)count {
    // 如果下拉刷新，则初始化模型数组
    if (page == 0) {
        self.recentArray = [[NSMutableArray alloc] init];
    }
    
    

    // 初始化请求参数,按时间降序请求近期活动
    NSDictionary *paramters = @{@"s_id": [UserInfoModel shareInstance].stu_id, @"activity_college": @(1), @"activity_type": @(1), @"activity_status": @(1), @"sort_type": @(1), @"page": @(page), @"count": @(count)};

    // 网络请求
    [[NetworkTool shareInstance] requireMethodType:POSTType
                                         URLString:@"SDSY/getActivity"
                                        parameters:paramters
                                           success:^(NSDictionary *respondDictionary) {
                                               // 1.储存数据
                                               for (NSDictionary *dic in respondDictionary[@"Activities"]) {
                                                   ActivityModel *model = [[ActivityModel alloc] initWithDictionary:dic];
                                                   [self.recentArray addObject:model];
                                               }
                                               [self.tableView reloadData];

                                               // 2.检查是否正常加载
                                               if ([respondDictionary[@"Activities"] count] < count) {
                                                   // 没有更多数据
                                                   [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                               }else {
                                                   // 正常结束刷新
                                                   [self.tableView.mj_footer endRefreshing];
                                               }
                                               [self.tableView.mj_header endRefreshing];
                                           } failure:^(NSError *error) {
                
                [self updateFailed];
            }];
}

#pragma mark - 事件监听
// 消息按钮
- (void)messageBtnTapped {
    //创建controller
    NoticeTableViewController* noticetv=[NoticeTableViewController new];
    [self.navigationController pushViewController:noticetv animated:YES];
    
}

// 签到按钮
- (void)signinBtnTapped {
    // 1.获取物理摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        // 如果能获取到设备,判断摄像头权限
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

        if (status == AVAuthorizationStatusNotDetermined) {
            // 如果权限还未确定,则请求相机权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    // 如果同意了相机权限
                    NSLog(@"用户同意了相机权限");

                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 跳转扫描界面
                        SigninViewController *signinViewController = [[SigninViewController alloc] init];
                        [self.navigationController pushViewController:signinViewController animated:true];
                    });
                } else {
                    // 如果拒绝了权限
                    NSLog(@"用户拒绝了相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) {
            // 如果已经同意了相机权限,跳转扫描界面
            SigninViewController *signinViewController = [[SigninViewController alloc] init];
            [self.navigationController pushViewController:signinViewController animated:true];
        } else if (status == AVAuthorizationStatusDenied) {
            // 如果权限被拒绝
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                     message:@"请去-> [设置 - 隐私 - 相机 - 尚德书院] 打开访问开关"
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:true completion:nil];
        } else if (status == AVAuthorizationStatusRestricted) {
            // 如果系统相机权限未开启
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                     message:@"由于系统权限未开启,无法打开摄像头"
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:true completion:nil];
        }

    } else {
        // 如果获取不到设备
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"⚠️ 警告"
                                                                                 message:@"未检测到摄像头"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:action];
        [self presentViewController:alertController animated:true completion:nil];
    }



}

// 活动预约按钮
- (void)orderActivityBtnTapped {
    OrderActivityController *orderActivityController = [[OrderActivityController alloc] init];
    [self.navigationController pushViewController:orderActivityController animated:true];
}

// 导师预约按钮
- (void)orderTeacherBtnTapped {
    OrderTeacherController *orderTeacherController = [[OrderTeacherController alloc] init];
    [self.navigationController pushViewController:orderTeacherController animated:true];
}

// 往期活动按钮
- (void)pastActivityBtnTapped {
    PastActivityViewController *pastActivityViewController = [[PastActivityViewController alloc] init];
    [self.navigationController pushViewController:pastActivityViewController animated:true];
}

// 活动分类按钮
- (void)classifyBtnTapped:(UIButton *)btn {
    // 1.取出点击btn的标题
    NSString *title = [btn titleForState:UIControlStateNormal];
    // 2.初始化要push的控制器
    OrderActivityController *orderActivityController = [[OrderActivityController alloc] init];
    // 3.检查哪个按钮被按下
    if ([title isEqualToString:@"博雅读书"]) {
        orderActivityController.activityType = 1;
    }else if ([title isEqualToString:@"博雅\"心情\""]) {
        orderActivityController.activityType = 2;
    }else if ([title isEqualToString:@"博雅实践"]) {
        orderActivityController.activityType = 3;
    }else if ([title isEqualToString:@"博雅讲坛"]) {
        orderActivityController.activityType = 4;
    }else if ([title isEqualToString:@"博雅修身"]) {
        orderActivityController.activityType = 5;
    }else if ([title isEqualToString:@"博雅视野"]) {
        orderActivityController.activityType = 6;
    }
    [self.navigationController pushViewController:orderActivityController animated:true];
}

- (void)showAnnounceInfoWithActivityID:(NSInteger)actID{
    [SVProgressHUD show];
    [[NetworkTool shareInstance] requireMethodType:GETType
                                         URLString:@"SDSY/getAnnounceInfo"
                                        parameters:@{@"act_id": @(actID)}
                                           success:^(NSDictionary *respondDictionary) {
                                               [SVProgressHUD dismiss];
                                               UIAlertController *alert = [UIAlertController alertControllerWithTitle:respondDictionary[@"newDetail"][@"name"] message:respondDictionary[@"newDetail"][@"act_news"] preferredStyle:UIAlertControllerStyleAlert];
                                               UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                                               [alert addAction:done];
                                               
                                               [self presentViewController:alert animated:true completion:nil];
                                           } failure:^(NSError *error) {
                                               [SVProgressHUD dismiss];
                                               [SVProgressHUD showfailed];
                                           }];
}

#pragma mark - TableView回调方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        // 推荐活动
        return [tableView cellHeightForIndexPath:indexPath model:self.recommandArray[indexPath.row] keyPath:@"model" cellClass:[ActivityCell class] contentViewWidth:SCREEN_WIDTH];
    } else {
        // 近期活动
        return [tableView cellHeightForIndexPath:indexPath model:self.recentArray[indexPath.row] keyPath:@"model" cellClass:[ActivityCell class] contentViewWidth:SCREEN_WIDTH];
    }

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"推荐活动";
    }else {
        return @"近期活动";
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    // 取出cell
    ActivityCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    // 弹出活动详情页
    ActivityInfoViewController *activityInfoViewController = [[ActivityInfoViewController alloc] init];
    activityInfoViewController.activityID = cell.model.activity_id;
    [self.navigationController pushViewController:activityInfoViewController animated:true];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0) {
        // 推荐活动
        return self.recommandArray.count;
    } else {
        // 近期活动
        return self.recentArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        // 推荐活动
        ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"COMCELL"];
        if (cell==nil) {
            cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"COMCELL"];
        }
        cell.model = self.recommandArray[indexPath.row];
        return cell;
    } else {
        ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RECCELL"];
        if (cell==nil) {
            cell = [[ActivityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RECCELL"];
        }
        // 近期活动
        cell.model = self.recentArray[indexPath.row];
        return cell;

    }

}

#pragma mark - Banner回调方法
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    // 取出模型
    BannerModel *model = self.bannerArray[index];
    
    if(model.status){
        // 公告
        [self showAnnounceInfoWithActivityID:model.banner_id];
    }else{
        //显示控制器
        ActivityInfoViewController *activityInfoViewController = [[ActivityInfoViewController alloc] init];
        activityInfoViewController.activityID = model.banner_id;
        
        [self.navigationController pushViewController:activityInfoViewController animated:true];
    }



}

@end
